/*
 * CatalogueFacadeBean.java
 *
 * Created on 8 May 2007, 00:14
 * Copyright (C) 2007   Yuezhong Zhang
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package usyd.comp5348;

import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Yuezhong Zhang  305275631
 * @since version 2.0 for assignment 2
 * change made to :
 * 1: add logger support for easy debug, enterprise application is very hard to
 *    debug, we cannot only depend on the println.
 * 2: modified create video, when a new catatlogu created, it is flushed to database
 *    immediately, so that we can get it's id, otherwise, we cannot get it's id if it only
 *    exist in memoory, because we set the id is auto generated.(such happen only when write
 *    entity to database.
 * 3: fixed naming query errors
 * 4: no entity object is return to client
 * 5: removed redundant exceptions,
 *
 * @author Henry Petersen
 * Create version 1.0
 */
@Stateless(mappedName="ejb/Catalogue")
public class CatalogueFacadeBean implements CatalogueFacadeRemote, CatalogueFacadeLocal {
    private Logger  logger = Logger.getLogger("usyd.comp5348.CatalogueFacadeBean");
    @PersistenceContext
    private EntityManager em;
    
    /** Creates a new instance of CatalogueFacadeBean */
    public CatalogueFacadeBean() {
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public int createVideo(Catalogue video){
        em.persist(video);
        em.flush();   //need to flush, otherwise Id isn't generated
        return video.getId();
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void modifyVideo(Catalogue video)  throws CatalogueException{
        CatalogueException ext;
        if(video.getId() < 0){
            ext = new CatalogueException("Catalogue with an invalid id");
            logger.warning(ext.getMessage());
            throw ext;
        }
        Catalogue cat = getVideoById(video.getId());
        if(cat == null){
            ext =  new CatalogueException("Couldn't find specified catalgoue with id="+ video.getId());
            logger.warning(ext.getMessage());
            throw ext;
        }
        cat.setCatalogueNumber(video.getCatalogueNumber());
        cat.setDirector(video.getDirector());
        cat.setGenre(video.getGenre());
        cat.setPrice(video.getPrice());
        cat.setTitle(video.getTitle());
        em.merge(cat);
        em.flush();
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void deleteVideo(int id) throws CatalogueException {
        Catalogue cat = getVideoById(id);
        if(cat != null) {
            em.remove(cat);
            em.flush();
        }else {
            CatalogueException ext = new CatalogueException("Failed to delete video="+id +",it might not exist");
            logger.warning(ext.getMessage());
            throw ext;
        }
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Catalogue getVideoById(int id) {
        return em.find(Catalogue.class, id);
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Catalogue getVideoByCatalogueNumber(String catalogueNumber){
        Query query = em.createNamedQuery("queryByCatalogueNumber");
        query.setParameter("catalogueNumber", catalogueNumber);
        Catalogue cat = (Catalogue) query.getSingleResult();
        return cat;
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Collection<Catalogue> getVideosByDirector(String director)  {
        Collection<Catalogue> rlist = new ArrayList<Catalogue>();
        Query query = em.createNamedQuery("queryByDirector");
        query.setParameter("director",director);
        for(Object obj : query.getResultList()) {
            if(obj instanceof Catalogue){
                rlist.add((Catalogue)obj);
            }
        }
        return rlist;
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Collection<Catalogue> getVideosByGenre(String genre){
        Collection<Catalogue> rlist = new ArrayList<Catalogue>();
        Query query = em.createNamedQuery("queryByGenre");
        query.setParameter("genre",genre);
        for(Object obj : query.getResultList()) {
            if(obj instanceof Catalogue){
                rlist.add((Catalogue)obj);
            }
        }
        return rlist;
        
    }
}
